package com.esender.monitor.task;

import com.esender.monitor.client.CacheClient;
import com.esender.monitor.util.MailUtil;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Set;

/**
 * 查询用户余额情况
 */
@Component
@Slf4j
public class MonitorClientBalanceTask {
    // 队列消息限制
    private final long BALANCE_LIMIT = 5000000;
    // 查询队列名称的固定pattern
    private final String BALANCE_PATTERN = "client_balance:*";

    private final String BLANCE = "balance";

    private final String EMAIL = "extend1";
    String text = "客户您好，您在【短信烽火云平台】内的余额仅剩%s元，请您及时充值，避免影响您短信的正常发送！！！";

    String subject = "【短信烽火云平台】余额不足";

    @Autowired
    private CacheClient cacheClient;
    @Autowired
    private MailUtil mailUtil;
    @XxlJob("monitorClientBalanceTask")
    public void monitor() throws Exception {
        // 1、查询客户余额信息
        Set<String> keys = cacheClient.keys(BALANCE_PATTERN);
        // 这里的每一个key就是每一个的客户

        for (String key:keys) {
            // 获取每个客户的信息
            Map map = cacheClient.hGetAll(key);
            // 获取客户余额
            Long balance = Long.parseLong(map.get(BLANCE) + "");
            if (balance < BALANCE_LIMIT){
                String email = (String) map.get(EMAIL);
                mailUtil.sendEmail(email,subject,String.format(text,balance / 1000));
            }
        }
    }
}
